<?php

namespace App\Imports\Shop;

use App\Kuafu\Shop\Model\ShopAttributeCategoryModel;
use App\Kuafu\Shop\Model\ShopAttributeMappingModel;
use App\Kuafu\Shop\Model\ShopAttributeModel;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class ShopAttributeGoodsNameImport implements ToCollection
{
    public static Command $command;

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        // 门店属性值列表
        $shopAttributeList = ShopAttributeModel::query()
                                               ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_4)
                                               ->get();

        // 售卖品类  多选 炸串 炸鸡 主食 包装饮品 景区精选
        $friedChickenId     = $shopAttributeList
            ->where('name', '炸鸡')->first();
        $stapleFood         = $shopAttributeList
            ->where('name', '主食')->first();
        $scenicSpotSelected = $shopAttributeList
            ->where('name', '景区精选')->first();

        $createData = [];
        $collection->each(function ($row, $index) use (
            $friedChickenId,
            $stapleFood,
            $scenicSpotSelected,
            &$createData
        ) {
            if (isset($row[0]) && $row[3]) {
                $shopId    = $row[0];
                $goodsName = $row[3];

                if (in_array($goodsName, ['超级大鱿鱼', '夸父大肉串', '香辣大鸡排', '街头大面筋'])) {// 景区精选
                    $attributeId = $scenicSpotSelected->id ?? 0;
                } elseif (in_array($goodsName, ['布袋馍'])) {// 主食
                    $attributeId = $stapleFood->id ?? 0;
                } else {// 炸鸡
                    $attributeId = $friedChickenId->id ?? 0;
                }
                if ($attributeId) {
                    $createData[$shopId . '-' . $attributeId] = [
                        'shopId'      => $shopId,
                        'attributeId' => $attributeId,
                        'value'       => '',
                        'createdAt'   => time(),
                    ];
                }
            }
        });
        if ($createData) {
            $chunk = array_chunk($createData, 500);
            foreach ($chunk as $value) {
                ShopAttributeMappingModel::query()->insert($value);
            }
        }
    }

}
